package com.system.connect.springboot_flowers.controller;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.system.connect.springboot_flowers.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * AI聊天控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/ai")
public class AiController {

    private static final String API_KEY = "sk-df225849bbc74813b7e4ef604ae7ed1f";

    /**
     * AI聊天接口
     * @param request 包含messages的请求体
     * @return 统一响应格式
     */
    @PostMapping("/chat")
    public R<String> chat(@RequestBody Map<String, List<Map<String, String>>> request) {
        try {
            List<Map<String, String>> messages = request.get("messages");
            if (messages == null || messages.isEmpty()) {
                return R.error("消息不能为空");
            }

            // 构建消息列表
            List<Message> messageList = new ArrayList<>();
            
            // 添加系统角色消息
            messageList.add(Message.builder()
                    .role(Role.SYSTEM.getValue())
                    .content("你是一个智能助手")
                    .build());

            // 添加历史消息
            for (Map<String, String> msg : messages) {
                String role = msg.get("role");
                String content = msg.get("content");
                if (role != null && content != null) {
                    messageList.add(Message.builder()
                            .role(role)
                            .content(content)
                            .build());
                }
            }

            // 调用百炼模型
            Generation gen = new Generation();
            QwenParam param = QwenParam.builder()
                    .model(Generation.Models.QWEN_TURBO)
                    .messages(messageList)
                    .resultFormat(QwenParam.ResultFormat.MESSAGE)
                    .apiKey(API_KEY)
                    .build();

            // 获取AI回复
            String response = gen.call(param).getOutput().getChoices().get(0).getMessage().getContent();
            
            return R.success(response);
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            log.error("调用百炼模型失败：{}", e.getMessage());
            return R.error("AI服务暂时不可用，请稍后再试");
        } catch (Exception e) {
            log.error("处理请求失败：{}", e.getMessage());
            return R.error("服务器内部错误");
        }
    }
} 